package com.chuantou.yuba.ui.widget;

import com.chuantou.yuba.R;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 加载视图
 * 
 * @author dl1001
 * 
 */
public class LoadingView extends FrameLayout implements OnClickListener {
	private ProgressBar mProgressBar;
	private TextView mMessageView;
	private Style mStyle;
	private OnClickListener mRetryListener;

	public LoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		setupViews();
	}

	public LoadingView(Context context, AttributeSet attrs) {
		super(context, attrs);
		setupViews();
	}

	public LoadingView(Context context) {
		super(context);
		setupViews();
	}

	private void setupViews() {
		LayoutInflater.from(getContext()).inflate(R.layout.loading_layout, this, true);
		mProgressBar = (ProgressBar) findViewById(R.id.progress);
		mMessageView = (TextView) findViewById(R.id.message);
		setClickable(true);
		setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == this && mStyle == Style.ERROR) {
			if (mRetryListener != null) {
				mRetryListener.onClick(v);
			}
		}
	}

	public void setStyle(Style style, String message) {
		this.mStyle = style;
		switch (style) {
		case LOADING:
			mProgressBar.setVisibility(View.VISIBLE);
			mMessageView.setVisibility(View.GONE);
			break;
		case EMPTY:
			mProgressBar.setVisibility(View.GONE);
			mMessageView.setVisibility(View.VISIBLE);
			message = TextUtils.isEmpty(message) ? getContext().getString(R.string.no_content) : message;
			mMessageView.setText(message);
			break;
		case ERROR:
			mProgressBar.setVisibility(View.GONE);
			mMessageView.setVisibility(View.VISIBLE);
			if (TextUtils.isEmpty(message)) {
				mMessageView.setText(R.string.message_loading_error);
			} else {
				mMessageView.setText(message);
			}
			break;
		default:
			break;
		}
	}

	public void setOnRetryListener(OnClickListener l) {
		this.mRetryListener = l;
	}

	public enum Style {
		LOADING, EMPTY, ERROR
	}

}
